import HttpService from "../service/baseHttp";
export function typeOf(obj) {
    const toString = Object.prototype.toString;
    const map = {
        "[object Boolean]": "boolean",
        "[object Number]": "number",
        "[object String]": "string",
        "[object Function]": "function",
        "[object Array]": "array",
        "[object Date]": "date",
        "[object RegExp]": "regExp",
        "[object Undefined]": "undefined",
        "[object Null]": "null",
        "[object Object]": "object",
        "[object File]": "file"
    };
    return map[toString.call(obj)];
}
export function convertObj(data = {}, temp = {}) {
    if (typeOf(data) !== "object") return;
    const result = [];
    const converObj = function(obj, prefix) {
        const type = typeOf(obj);
        if (type === "object") {
            Object.keys(obj).forEach(function(key) {
                converObj(this[key], prefix ? `${prefix}[${key}]` : key);
            }, obj);
        } else if (type === "array") {
            Object.keys(obj).forEach(function(key) {
                converObj(this[key], prefix);
            }, obj);
        } else {
            if (obj === undefined || obj === null) obj = "";
            result.push({
                key: prefix,
                value: obj
            });
        }
    };
    converObj(data);
    return result;
}

export const FSAPI = {
    async download(url, formdata = {}, options = "POST") {
        if (typeof options !== "object") {
            options = { method: options };
        }
        options.method = options.method || "POST";
        const method = options.method.toLowerCase();
        if (!options.ajax) {
            formdata = convertObj(formdata);
            const fragment = document.createDocumentFragment();
            const form = document.createElement("form");
            const token = global.AUTH_TOKEN;
            form.action = url;
            form.style.display = "none";
            form.target = "";
            form.method = method;
            formdata.push(
                {
                    key: "Authorization",
                    value: token
                },
                {
                    key: "token",
                    value: token
                },
                {
                    key: "contextId",
                    value: global.SYSID
                }
            );
            for (let val of formdata) {
                const input = document.createElement("input");
                input.name = val.key;
                input.value = val.value;
                input.type = "hidden";
                form.appendChild(input);
            }
            fragment.appendChild(form);
            document.body.appendChild(fragment);
            form.submit();
            document.body.removeChild(form);
            return;
        }
        if (method === "get") {
            formdata = [{ params: formdata, responseType: "blob" }];
        } else {
            formdata = [formdata, { responseType: "blob" }];
        }
        return HttpService[method](url, ...formdata).then(res => {
            const fileType = { type: options.type } || undefined;
            const blob = new Blob([res], fileType);
            if (options.print) {
                FSAPI.printPage(blob, "blob");
                return;
            }
            const link = document.createElement("a"),
                fileName = options.fileName || "download.xls";
            if ("download" in link) {
                // 非IE下载
                link.download = fileName;
                link.style.display = "none";
                link.href = URL.createObjectURL(blob);
                document.body.appendChild(link);
                link.click();
                URL.revokeObjectURL(link.href);
                document.body.removeChild(link);
            } else {
                // IE10+下载
                navigator.msSaveBlob(blob, fileName);
            }
        });
    },

    printPage(data = "", type = "url") {
        let oWin = null;
        if (type === "url") {
            oWin = window.top.open(data, "_blank");
        }
        if (type === "html") {
            oWin = window.top.open("about:blank", "_blank");
            oWin.document.write(data);
        }
        if (type === "binary" && window.URL) {
            oWin = window.top.open(URL.createObjectURL(data), "_blank");
        }

        if (type === "blob" && window.URL) {
            // var reader = new FileReader();
            // reader.readAsDataURL(data);
            // reader.onload = function (event) {
            //     let result = event.target.result;
            //     oWin = window.top.open(result, '_blank');
            // }
            let url = window.URL.createObjectURL(data);
            oWin = window.top.open(url, "_blank");
        }
        // try {
        //     oWin.print();
        // } catch (err) {
        //     oWin.document.execCommand('print');
        // }
        return oWin;
    }
};
